let key = 'CetSoftEEMSysWeb'; //密钥
let iv = '1934577290ABCDEF1264147890ACAE45';
const axios = require('axios');
const {encrypt} = require('./aes');
axios.defaults.withCredentials = true;
let baseUrl = 'https://pynhcx.jnu.edu.cn/ibsjnuweb';

function time(){
  let date = new Date();
  return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
}

async function login(id){
  //pw为密码加密后
  let pw = encrypt(`${id}`, key);
  let login = await axios({
    method: 'post',
    url: `${baseUrl}/WebService/JNUService.asmx/Login`,
    data: {
      password: `${pw}`,
      user: `${id}`
    }
  });
  // console.log(login.data);
  // let header = login.headers;
  // let cookie = header['set-cookie'][0];
  console.log(pw);
}

async function balance(id) {
  //pw为密码加密后
  let pw = encrypt(`${id}`, key);
  let login = await axios({
    method: 'post',
    url: `${baseUrl}/WebService/JNUService.asmx/Login`,
    data: {
      password: `${pw}`,
      user: `${id}`
    },
    header: {
      'Content-Type': 'application/json; charset=utf-8',
      'origin': 'https://pynhcx.jnu.edu.cn',
      'referer': 'https://pynhcx.jnu.edu.cn/ibsjnuweb/',
    }
  });
  let header = login.headers;
  let cookie = header['set-cookie'][0];
  let token = {
    userID: login.data.d.ResultList[0].customerId,
    tokenTime: time()
  }
  token = JSON.stringify(token);
  // token = CryptoJS.AES.encrypt(token, "CetSoftEEMSysWeb").toString();
  token = encrypt(token, "CetSoftEEMSysWeb");
  token = encodeURI(token);
  console.log(token);


  let price = await axios({
    method:'post',
    url:`${baseUrl}/WebService/JNUService.asmx/GetAccountBalance`,
    headers: {
      "Cookie" : `${cookie.slice(0,43)} jnu-lp=${pw.slice(0,22)}%3D%3D`,
      "Content-Type": "application/json; charset=UTF-8",
      "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36 Edg/89.0.774.50',
      "Token": token,
      "DateTime": `${time()}`
    }
  })
  // console.log(`${id}水电费：${price.data}`);
  price = price.data;
  // console.log(typeof(price));
  if (typeof(price) == 'object') {
    return price.d.balance;
  }else{
    return false;
  }
}


// balance('T4080A').then(res => {
//   console.log(res);
// })

// balance('T4080A');
// balance('T40805');

module.exports = {balance}